import sys
import os
from http import HTTPStatus
from io import BytesIO

from dashscope import ImageSynthesis
from docx import Document
import requests

from core.config import settings

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from typing import List, Optional

from langchain.agents import create_openai_functions_agent, AgentExecutor
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain_community.utilities import SQLDatabase
import os
import dashscope
import ast

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.tools import Tool, StructuredTool

# 修复：使用绝对导入（假设当前工作目录为项目根目录）
# 使用相对导入
from core.llm import get_default_llm
from tools.sql_tool import SqlTool


def create_analys_agent():
    json = []

    sqltool = SqlTool()
    query = sqltool.get_query()
    slides=query["slides"]
    outline = {"title":query["title"]}
    for slide in slides:
        element = sqltool.get_slide( slide["detail"])
        json.append( element)
    outline["slides"] = json
    return generate_word( outline)

def generate_image( prompt: str) -> Optional[BytesIO]:


    print('----sync call, please wait a moment----')
    rsp = ImageSynthesis.call(api_key=settings.LLM_API_KEY,
                          model="wanx2.1-t2i-turbo",
                          prompt=prompt,
                          n=1,
                          size='1024*1024')
    print('response: %s' % rsp)
    if rsp.status_code == HTTPStatus.OK:
    # 在当前目录下保存图片
        for result in rsp.output.results:
            response = requests.get(result.url)
            return BytesIO(response.content)
    else:
        print('sync_call Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))

def generate_word(content):
    # 创建一个新的Word文档
    doc = Document()
    # 添加标题
    doc.add_heading(content["title"], 0)
    for slide in content["slides"]:
        p = doc.add_paragraph(slide["title"])
        run = p.add_run()
        run.add_picture(generate_image(f"创建一张体现'{slide['image']}'的统计图表,其中的数据来自{slide['data']}"))
        run.add_text(slide["detail"])

    doc.save(f"{content['title']}.docx")
    return f"{content['title']}.docx"